package com.yc.upload.web;

import com.yc.upload.bean.Result;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;

@RestController
//@ConfigurationProperties(prefix = "static/upload")
@ConfigurationProperties(prefix = "upload")
@Data
public class UploadDo {

    Map<String,String> mapping;

    @PostMapping("upload/{webPath}.do")
    public Result upload(@PathVariable String webPath,
                         @RequestParam("file") MultipartFile file) throws IOException {
        String dirPath = mapping.get(webPath);
        String filename = file.getOriginalFilename();
        String suffix = filename.replaceAll(".+(\\.\\w+)","$1");
        String prefix = UUID.randomUUID().toString();
        filename = prefix + suffix;
        String filepath = dirPath + "/" + filename;
        file.transferTo(new File(filepath));
        webPath = webPath + "/" + filename;
        return new Result(1, "文件上传成功!", webPath);
    }
}
